from django.contrib import admin
from django.utils import timezone

from flowers.base import BaseAdmin

from .models import Article, Tag


@admin.register(Tag)
class TagAdmin(BaseAdmin):
    list_display = ["name", "created_at", "updated_at"]
    search_fields = ["name"]


@admin.register(Article)
class ArticleAdmin(BaseAdmin):
    list_display = ["title", "tag_list", "published", "published_at"]
    search_fields = ["title", "slug"]
    autocomplete_fields = ["tags"]
    date_hierarchy = "published_at"

    def tag_list(self, obj):
        return "、".join(i.name for i in obj.tags.all())

    tag_list.short_description = "标签"

    def save_model(self, request, obj, form, change):
        if not getattr(obj, "published_at", None) and obj.published:
            obj.published_at = timezone.now()
        return super().save_model(request, obj, form, change)
